package com.qf.day4.huihua;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @date 2022/3/28
 * @desc
 */
@WebServlet("/cookie1")
public class CookieDemoServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");

        //得到输出流 指向浏览器的流
        PrintWriter writer = resp.getWriter();

        //得到 客户端发送来的cookie   是一个数组
        Cookie[] cookies = req.getCookies();

        for(int i=0;cookies!=null&&i<cookies.length;i++){
            // 遍历cookie 数组 得到咱们想要的cookie
            String name = URLDecoder.decode(cookies[i].getName(),"UTF-8");

            // 判断是不是咱们需要的cookie
            if(name.equals("lastTime")){
                //是咱们需要的cookie   就得到该cookie 的值
                String value = URLDecoder.decode(cookies[i].getValue(),"UTF-8");

                // 把这个值写到浏览器
                writer.println(value);
            }
        }

        // 把本次的访问时间  通过cookie 写给浏览器
        Date date = new Date();
        // 创建cookie  对象  把本次的访问时间存到cookie
        Cookie lastTime = new Cookie(URLEncoder.encode("lastTime","UTF-8"), URLEncoder.encode(date.toLocaleString(),"UTF-8"));

        // 设置cookie 的有效时间
        lastTime.setMaxAge(60);   // 单位是 秒
        //发送cookie 到浏览器
        resp.addCookie(lastTime);
    }
}
